

#import "PercentCurrentModel.h"
#import "PercentCurrentLinePlot.h"
#import "MetricsItem.h"



@implementation PercentCurrentLinePlot

#define oneDayInterval 86400 //60*60*24
#define initNumberOfDaysDisplayed 183

#define rulerPlotIdentifier @"rulerPlotIdentifier"
#define numberOfMarkerPlotSymbols 2
#define kRepeat 20 //repeat count, used for animation
#define kFrameRate 20  // frames per second, used for animation



@synthesize delegate;

- (id)init
{
    self = [super init];
    if (self) { 
        metricsData = nil;  
    }
    
    return self;
}

-(void) initStartDate{
    
    NSDate * today = [[NSDate alloc]init];
    
    initStartDate = [today dateByAddingTimeInterval:(oneDayInterval *initNumberOfDaysDisplayed * -1)];
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyMMdd"];
    initStartDateString = [df stringFromDate:initStartDate];
    
   // NSLog(@"PercentCurrent initStartDateString = %@",initStartDateString);  
}

- (id) initWithMetricsData:(NSMutableDictionary *) data {
    
    metricsData=data;
    
    [self initStartDate];
    
    dailyKeys=[metricsData allKeys];
    
    dailyKeys = [dailyKeys sortedArrayUsingSelector:@selector(compare:)];
    
    NSInteger initStartIndex = [dailyKeys indexOfObject:initStartDateString];    
    
    totalNoOfDataPoints=[metricsData count];
    
    dailyKeysInRange=[[NSMutableArray alloc]init];
      
    for (int i=initStartIndex; i <totalNoOfDataPoints; i++){
        [dailyKeysInRange addObject:[dailyKeys objectAtIndex:i]];
           
    }
    
    NoOfDataPointsInRange = [dailyKeysInRange count];
    //initial position of ruler; 
    rulerIndex = NoOfDataPointsInRange -1; //today
    rulerDateString = [dailyKeysInRange objectAtIndex:rulerIndex]; 
    
    NoOfDataPointsInRange = [dailyKeysInRange count]; 
    
    isShowpriorYear=NO;
    isShowPercent91DaysDelinquent=NO;
    rangeChanged = NO;
    rulerEnabled = NO;
    return self;
    
}


-(NSUInteger) numberOfRecordsForPlot:(CPTPlot *)plot{
    if ([ (NSString*)plot.identifier isEqualToString:rulerPlotIdentifier]) {
        return numberOfMarkerPlotSymbols;
            
    }
    else {
        return NoOfDataPointsInRange;
                    
    }
       
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index 
{  
    NSNumber *num = nil; 
    
    MetricsItem *startData,*endData,*indexData;
    NSString *refDateString = [dailyKeysInRange objectAtIndex:0];
    MetricsItem *refData = [metricsData objectForKey:refDateString];
    index=index>=NoOfDataPointsInRange ? NoOfDataPointsInRange-1:index;
    NSString *indexDateString = [dailyKeysInRange objectAtIndex:index];
    endData = [metricsData objectForKey:indexDateString];
    
    if (index < [animationStartDailyKeys count]){
        NSString *startDateString = [animationStartDailyKeys objectAtIndex:index];
        startData = [metricsData objectForKey: startDateString];
    } else {
        startData = nil;  
    }
    
    indexData= startData?startData:endData;
    
    NSDictionary *unitDict = [animationUnit objectAtIndex:index];
    
    if ([(NSString *)plot.identifier isEqualToString:percentCurrentIdentifier]){ 
        NSNumber *unitPercent = [unitDict objectForKey:@"current"];
       
       
       if ( fieldEnum == CPTScatterPlotFieldY ){
           
           float percent = [indexData.percentCurrent floatValue];
           float currentPercent = 
           percent + [unitPercent floatValue] * (timerCount+1);
           num = [NSNumber numberWithFloat:currentPercent];
           
           
           
       } else if (fieldEnum == CPTScatterPlotFieldX){
           num=[NSNumber numberWithFloat: (refData.timeIntervalSinceToday - endData.timeIntervalSinceToday)];
       }
   
   }
    
    if ([(NSString *)plot.identifier isEqualToString:priorYearIdentifier]){ 
         NSNumber *unitPercentPrior = [unitDict objectForKey:@"priorYear"];
        
        if ( fieldEnum == CPTScatterPlotFieldY ){
            float percent = [indexData.priorYearPercentCurrent floatValue];
            float priorPercent = 
            percent + [unitPercentPrior floatValue] * (timerCount+1);
            num = [NSNumber numberWithFloat:priorPercent];
            
        } else if (fieldEnum == CPTScatterPlotFieldX){
            num=[NSNumber numberWithFloat: (refData.timeIntervalSinceToday - endData.timeIntervalSinceToday)];
        }    
    }  
    if ([(NSString *)plot.identifier isEqualToString:percentOver91DaysDelinquentIdentifier]){ 
        
        NSNumber *unitPercentOver91DaysDelinquent = [unitDict objectForKey:@"percentOver91DaysDelinquent"];
        
        if ( fieldEnum == CPTScatterPlotFieldY ){
            float percentOver91DaysDelinquent = [indexData.percent90OverDaysDelinquent floatValue];
            percentOver91DaysDelinquent= percentOver91DaysDelinquent + [unitPercentOver91DaysDelinquent floatValue] * (timerCount+1);
            num = [NSNumber numberWithFloat:percentOver91DaysDelinquent];
            
        } else if (fieldEnum == CPTScatterPlotFieldX){
            num=[NSNumber numberWithFloat: (refData.timeIntervalSinceToday - endData.timeIntervalSinceToday)];
        }    
    } 
    if ([(NSString *)plot.identifier isEqualToString:rulerPlotIdentifier]){
        
        if ( fieldEnum == CPTScatterPlotFieldY ) 
        {
            switch (index) {
                case 0:
                    num = [NSNumber numberWithInt:0];
                    break; 
                case 1:
                    num = [NSNumber numberWithInt:100];
                    break;    
                default:
                    num = [NSNumber numberWithInt:0];
                    break;
            }
        } 
        else if (fieldEnum == CPTScatterPlotFieldX) 
        {   
            
            NSString *refDateString = [dailyKeysInRange objectAtIndex:0];
            MetricsItem *refData = [metricsData objectForKey:refDateString];
            MetricsItem *rulerData = [metricsData objectForKey:rulerDateString];
            
            num=[NSNumber numberWithFloat: (refData.timeIntervalSinceToday - rulerData.timeIntervalSinceToday)];
        }
    }    
    return num;
}
- (void)removePlot:(NSString *)plotIdentifier{
    
    if ([plotIdentifier isEqualToString:priorYearIdentifier]){ 
        [graph removePlot:priorYearPlot];
        isShowpriorYear = NO;
    }
    else if ([plotIdentifier isEqualToString:percentOver91DaysDelinquentIdentifier]){ 
        [graph removePlot:percent91DaysDelinquentPlot];
        isShowPercent91DaysDelinquent = NO;
    }
    
}

- (void)addPlot:(NSString *)plotIdentifier{
    
    if ([plotIdentifier isEqualToString:priorYearIdentifier]){ 
        [graph addPlot:priorYearPlot];
        isShowpriorYear = YES;
    }else if ([plotIdentifier isEqualToString:percentOver91DaysDelinquentIdentifier]){ 
        [graph addPlot:percent91DaysDelinquentPlot];
        isShowPercent91DaysDelinquent = YES;
    }
    
}

#pragma mark - CPTPlotSpace Delegate Methods
// This implementation of this method will put the line graph in a fix position so it won't be scrollable.

-(CPTPlotRange *)plotSpace:(CPTPlotSpace *)space willChangePlotRangeTo:(CPTPlotRange *)newRange forCoordinate:(CPTCoordinate)coordinate 
{
    
    if (coordinate == CPTCoordinateY) {
        return ((CPTXYPlotSpace *)space).yRange;
    }
    else
    {   
        //return newRange; //allow horizontal scrolling
        return ((CPTXYPlotSpace *)space).xRange;  //disable horizontal scrolling
    }
}

// Assign different color to the touchable line symbol.
- (void)applyRulerPlotColor{
    
    CPTMutableLineStyle *rulerLineStyle = [CPTMutableLineStyle lineStyle];
    rulerLineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:4.0f], nil];
    rulerLineStyle.lineColor = [CPTColor cyanColor];
    //rulerLineStyle.lineColor = [CPTColor colorWithComponentRed:0.129 green:0.545 blue:0.894 alpha:1.0]; //RGB: 33-139-228  (blue) 
    rulerLineStyle.lineWidth = 2.0f;
    rulerPlot.dataLineStyle = rulerLineStyle;
    
}

// Highlight the touch plot when the user holding tap on the line symbol.
- (void)highlightRulerPlotColor{
    
    CPTMutableLineStyle *selectedRulerLineStyle = [CPTMutableLineStyle lineStyle];
    selectedRulerLineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:4.0f], nil];
    selectedRulerLineStyle.lineColor = [CPTColor yellowColor];
    selectedRulerLineStyle.lineWidth = 2.0f;
    rulerPlot.dataLineStyle = selectedRulerLineStyle;
}

-(void)removeRulerAnnotation{
    if ( symbolTextAnnotation ) {
        [graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
        symbolTextAnnotation = nil;
    };
}

-(void)displayRulerAnnotation
{
    
    if ( symbolTextAnnotation ) {
        [graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
        symbolTextAnnotation = nil;
    };
    
    
    
    // Setup a style for the annotation
    CPTMutableTextStyle *hitAnnotationTextStyle = [CPTMutableTextStyle textStyle];
    hitAnnotationTextStyle.color	= [CPTColor cyanColor];
    //hitAnnotationTextStyle.color = [CPTColor colorWithComponentRed:0.129 green:0.545 blue:0.894 alpha:1.0]; //RGB: 33-139-228  (blue) 
    hitAnnotationTextStyle.fontSize = 13.0f;
    hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
    
    NSString *refDateString = [dailyKeysInRange objectAtIndex:0];
    MetricsItem *refData = [metricsData objectForKey: refDateString];
    MetricsItem *rulerData = [metricsData objectForKey: rulerDateString];
    
  //  if ([delegate respondsToSelector:@selector(respondToValueChange:item:)]){
        
        [delegate respondToValueChange: self item: rulerData];
  //  }
    
    NSArray *anchorPoint = [NSArray arrayWithObjects:
                            [NSNumber numberWithFloat: (refData.timeIntervalSinceToday - rulerData.timeIntervalSinceToday)],
                            [NSNumber numberWithInt:110],nil];
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    //[dateFormat setDateStyle:NSDateFormatterMediumStyle];
    NSString *asOfDateString = [dateFormat stringFromDate:rulerData.itemDate];
    NSString *formattedPercent = [NSString stringWithFormat:@"%.02f", [rulerData.percentCurrent floatValue]];
    
    NSString *rulerString = [NSString stringWithFormat:@" %@%% - %@ \n" 
                             , formattedPercent,asOfDateString];
    
    // Now add the annotation to the plot area
    CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:rulerString style:hitAnnotationTextStyle];
    symbolTextAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
    
    //UIImage *popoverImage = [UIImage imageNamed:@"popover.png"];
    //textLayer.backgroundColor = [UIColor colorWithPatternImage:popoverImage].CGColor;
    textLayer.backgroundColor = [UIColor blackColor].CGColor;
    textLayer.frame = CGRectMake(0,0, 130, 20); 
    
    symbolTextAnnotation.contentLayer = textLayer;
    symbolTextAnnotation.displacement = CGPointMake(0.0f, -35.0f);
    [graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
    
    
}


// This method is call when user touch & drag the ruler plot
- (BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)point
{
    
    if (!rulerEnabled){
        [self applyRulerPlotColor];
        [self displayRulerAnnotation]; 
        rulerEnabled = YES;
        [graph addPlot:rulerPlot];
        [rulerPlot reloadData];
    }
    
    
    // Convert the touch point to plot area frame location
    CGPoint pointInPlotArea = [graph convertPoint:point toLayer:graph.plotAreaFrame];
    NSDecimal newPoint[2];
    [graph.defaultPlotSpace plotPoint:newPoint forPlotAreaViewPoint:pointInPlotArea];
    NSDecimalRound(&newPoint[0], &newPoint[0], 0, NSRoundPlain);
    
    int x = [[NSDecimalNumber decimalNumberWithDecimal:newPoint[0]] intValue];
    
    
    if (!rulerEnabled){
        [self applyRulerPlotColor];
        [self displayRulerAnnotation]; 
        rulerEnabled = YES;
        [graph addPlot:rulerPlot];
        [rulerPlot reloadData];
    }
    
    //int maxRange = initNumberOfDaysDisplayed;
    int maxRange = NoOfDataPointsInRange;
    
    /*if ((rangeChanged) && (NoOfDataPointsInRange > initNumberOfDaysDisplayed)) 
     maxRange = NoOfDataPointsInRange; */
    
    int totalRange = oneDayInterval*maxRange; 
    if (x > totalRange)
    {
        if (rulerIndex <= (NoOfDataPointsInRange-2)){
            rulerIndex = rulerIndex + 1;
        }
    } else if (x < 0){
        if (rulerIndex >=1){
            rulerIndex = rulerIndex - 1;
        }
    }
    
    else {
        //int totalRange = oneDayInterval*maxRange;
        //x =  x/(totalRange/NoOfDataPointsInRange);
        x =  x/oneDayInterval;       
        if (x < NoOfDataPointsInRange)
            rulerIndex = x;
    };
    
    
    selectedDateString = [dailyKeysInRange objectAtIndex:rulerIndex];
    rulerDateString = selectedDateString;
    //[self highlightRulerPlotColor];
    [self displayRulerAnnotation];
    [rulerPlot reloadData];
    
    return YES;
    
   
    
    
}



- (BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(id)event 
          atPoint:(CGPoint)point
{
    // Convert the touch point to plot area frame location
    CGPoint pointInPlotArea = [graph convertPoint:point toLayer:graph.plotAreaFrame];
    NSDecimal newPoint[2];
    [graph.defaultPlotSpace plotPoint:newPoint forPlotAreaViewPoint:pointInPlotArea];
    NSDecimalRound(&newPoint[0], &newPoint[0], 0, NSRoundPlain);
    
    int x = [[NSDecimalNumber decimalNumberWithDecimal:newPoint[0]] intValue];
    
 
    x =  x/oneDayInterval;
    
    if (rulerEnabled){
        [graph removePlot:rulerPlot];
        [self removeRulerAnnotation];
        rulerEnabled = NO;
    } else{
        rulerIndex = x;
        rulerDateString = [dailyKeysInRange objectAtIndex:x];
        [self applyRulerPlotColor];
        [self displayRulerAnnotation]; 
        rulerEnabled = YES;
        [graph addPlot:rulerPlot];
        [rulerPlot reloadData];
        
        
    }
    
    
    return YES;
}

- (BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceUpEvent:(id)event atPoint:(CGPoint)point
{
    
    // Convert the touch point to plot area frame location
    CGPoint pointInPlotArea = [graph convertPoint:point toLayer:graph.plotAreaFrame];
    NSDecimal newPoint[2];
    [graph.defaultPlotSpace plotPoint:newPoint forPlotAreaViewPoint:pointInPlotArea];
    NSDecimalRound(&newPoint[0], &newPoint[0], 0, NSRoundPlain);
    
    int x = [[NSDecimalNumber decimalNumberWithDecimal:newPoint[0]] intValue];
    int maxRange = initNumberOfDaysDisplayed;
    
    if ((rangeChanged) && (NoOfDataPointsInRange > initNumberOfDaysDisplayed)) 
        maxRange = NoOfDataPointsInRange; 
    
    int totalRange = oneDayInterval*maxRange; 
    
    if ((x > totalRange) || ( x < 0)){
        return NO;
    }
    else {
        
        int totalRange = oneDayInterval*maxRange;
        x =  x/(totalRange/NoOfDataPointsInRange);
        
        selectedDateString = [dailyKeysInRange objectAtIndex:x];
        
        rulerDateString = selectedDateString;
        rulerIndex = x;
        [self applyRulerPlotColor];
        return YES;
    };
    
}


# pragma CEISliderPlotDelegate
//change the date range responding to the range plot
-(void)respondToRangeChangeFromDate:(NSString *)newFromDateString toDate:(NSString *)newToDateString
{
    
    NSInteger startIndex = [dailyKeys indexOfObject:newFromDateString];
    NSInteger endIndex = [dailyKeys indexOfObject:newToDateString];
    //NSLog(@"newFromDateString=%@,startIndex=%i,newToDateString=%@,endIndex=%i",newFromDateString,startIndex,newToDateString,endIndex);
    
    int NoOfDaysInRange = endIndex - startIndex +1;;
    
    if (NoOfDaysInRange != NoOfDataPointsInRange)
        rangeChanged = YES;
    
    int gap = 1;
    if (NoOfDaysInRange > initNumberOfDaysDisplayed*1.5) {
        gap = (NoOfDaysInRange/initNumberOfDaysDisplayed)+1;
    };
    
    
    //for animation. Copy dailyKeysInRange as it will be changed soon.
    animationStartDailyKeys = [NSMutableArray arrayWithCapacity:2000]; 
    for (int s=0;s<NoOfDataPointsInRange;s++){
        [animationStartDailyKeys addObject:[dailyKeysInRange objectAtIndex:s]];
    };
    
    
    //refresh the current plot for the new range         
    NSMutableArray *displayDailyKeys  = [NSMutableArray arrayWithCapacity:5000];
    
    for (int idx= startIndex; idx < endIndex+1; idx++){
        [displayDailyKeys addObject:[dailyKeys objectAtIndex:idx]];
    };
    
    
    dailyKeysInRange = displayDailyKeys;
    NoOfDataPointsInRange = [dailyKeysInRange count];
    //NSLog(@"NoOfDaysInRange=%i, NoOfDataPointsInRange=%i",NoOfDaysInRange,NoOfDataPointsInRange);
    
    //set up animation data
    [self prepareAnimationData]; 
    
    
    if (rulerEnabled){
        rulerDateString = [dailyKeysInRange objectAtIndex:rulerIndex];
        [self displayRulerAnnotation];
    } 
    
    //-----------------------------------------------------
    //refresh the all collectors plot for the new range         
    NSMutableArray *displayAllCollectorsKeysInRange  = [NSMutableArray arrayWithCapacity:5000];
    for (int idx= startIndex; idx < endIndex+1; idx++){
        [displayAllCollectorsKeysInRange addObject:[dailyKeys objectAtIndex:idx]];
    };
    
    
    
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(oneDayInterval*0) 
                                                    length:CPTDecimalFromFloat(oneDayInterval* (NoOfDaysInRange-1))];
    
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x = axisSet.xAxis;
    
    x.majorIntervalLength = CPTDecimalFromFloat(oneDayInterval*30.0 * gap);
    
    NSDateFormatter *fromDateFormatter = [[NSDateFormatter alloc] init];
    [fromDateFormatter setDateFormat:@"yyyyMMdd"];
    NSDate *newFromDate = [fromDateFormatter dateFromString:newFromDateString]; 
    NSDate *refDate = newFromDate;   
    
    NSDateFormatter *refDateFormatter = [[NSDateFormatter alloc] init];
    [refDateFormatter setDateFormat:@"MM/dd/yy"];
    CPTTimeFormatter *timeFormatter =[[CPTTimeFormatter alloc] initWithDateFormatter:refDateFormatter];
    timeFormatter.referenceDate = refDate;
    x.labelFormatter = timeFormatter;
        
    //animation
    dataTimer = [NSTimer timerWithTimeInterval:0.5/kFrameRate
                                        target:self
                                      selector:@selector(newData:)
                                      userInfo:nil
                                       repeats:YES];
	[[NSRunLoop mainRunLoop] addTimer:dataTimer forMode:NSDefaultRunLoopMode];

     [rulerPlot reloadData];
};

-(void)newData:(NSTimer *)theTimer
{       
    
    [currentPlot reloadDataInIndexRange:NSMakeRange(0,NoOfDataPointsInRange)];
    [priorYearPlot reloadDataInIndexRange:NSMakeRange(0,NoOfDataPointsInRange)];
    [percent91DaysDelinquentPlot reloadDataInIndexRange:NSMakeRange(0,NoOfDataPointsInRange)];        
    timerCount++;
    if (timerCount >= kRepeat) {
        [theTimer invalidate];
        timerCount = 0;
    }
    
}
-(void)prepareAnimationData{
    
    //set up unit of change for animation
    animationUnit = [NSMutableArray arrayWithCapacity:2000]; 
    
    for (int r=0;r<NoOfDataPointsInRange;r++){
        
        MetricsItem *startData;
        MetricsItem *endData;
        MetricsItem *startData90;
        MetricsItem *endData90;
        float newPercent, newPercent90, newPercentPrior;
        float oldPercent, oldPercent90, oldPercentPrior;
        float diffPercent, diffPercent90, diffPercentPrior;
        float unitPercent, unitPercent90, unitPercentPrior;
        
        if (r < [animationStartDailyKeys count]){
            startData = [metricsData objectForKey:[animationStartDailyKeys objectAtIndex:r]];
                       //NSLog(@"2r=%i,startData",r);
        }
        else{ 
            startData = nil;
            startData90 = nil;
        }
        
        if (r < [dailyKeysInRange count]){
            endData = [metricsData objectForKey:[dailyKeysInRange objectAtIndex:r]];
        }
        else{
            endData = nil;
            endData90 = nil;
        }
        
        
        
        NSMutableDictionary *unitDict = [[NSMutableDictionary alloc] init];
        if (endData){
            newPercent = [endData.percentCurrent floatValue];
            newPercentPrior = [endData.priorYearPercentCurrent floatValue];
            newPercent90 = [endData90.percent90OverDaysDelinquent floatValue];           
        } else{  
            newPercent = 0;
            newPercentPrior = 0;
            newPercent90 = 0;
        }
        if (startData){
            oldPercent = [startData.percentCurrent floatValue];
            oldPercentPrior = [startData.priorYearPercentCurrent floatValue];
            oldPercent90 = [startData90.percent90OverDaysDelinquent floatValue];            
        } else{  
            oldPercent = 0;
            oldPercentPrior = 0;
            oldPercent90=0;
           
        }
        
        
        if ((endData) && (startData))
            diffPercent = newPercent - oldPercent;
        else diffPercent = 0;
        
        if ((endData) && (startData))
            diffPercentPrior = newPercentPrior - oldPercentPrior;
        else diffPercentPrior = 0;
        
        if ((endData) && (startData))
            diffPercent90 = newPercent90 - oldPercent90;
        else diffPercent90 = 0;
        
        
        unitPercent = diffPercent / kRepeat;
        unitPercentPrior = diffPercentPrior / kRepeat;
        unitPercent90 = diffPercent90 / kRepeat;
        
        [unitDict setObject:[NSNumber numberWithFloat:unitPercent] forKey:@"current"];
        [unitDict setObject:[NSNumber numberWithFloat:unitPercentPrior] forKey:@"priorYear"];
        [unitDict setObject:[NSNumber numberWithFloat:unitPercent90] forKey:@"percent90OverDaysDelinquent"];
        
        
        [animationUnit addObject:unitDict];
        
    }
    
}


- (void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme{
    
    
    CGRect bounds = layerHostingView.bounds;
    
    graph = [[CPTXYGraph alloc] initWithFrame:bounds];
    layerHostingView.hostedGraph = graph;
    layerHostingView.backgroundColor = [UIColor colorWithWhite:0.7f alpha:1.0f]; 
    
    CPTGradient *plotAreaGradient = [CPTGradient gradientWithBeginningColor:[CPTColor colorWithGenericGray:0.9f]endingColor:[CPTColor colorWithGenericGray:0.7f]];
    plotAreaGradient.angle = -90.0;
    graph.plotAreaFrame.plotArea.fill = [CPTFill fillWithGradient:plotAreaGradient]; 
    
    [graph applyTheme:theme];
    
    graph.plotAreaFrame.masksToBorder = NO;
    
    CPTMutableTextStyle *blackTextStyle = [[CPTMutableTextStyle alloc] init];
    
    blackTextStyle.color = [CPTColor colorWithComponentRed:0.2 green:0.2 blue:0.2 alpha:0.82]; //RGB:R51-G51-B51
	blackTextStyle.fontSize = 20.0;
    graph.titleTextStyle = blackTextStyle;
    graph.titleDisplacement = CGPointMake(0.0, 80.0); 
    graph.title = @"Percent Current";
    
    
    
    
    // change the chart layer orders so the axis line is on top of the bar in the chart.
    NSArray *chartLayers = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:CPTGraphLayerTypePlots],
                            [NSNumber numberWithInt:CPTGraphLayerTypeMajorGridLines], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeMinorGridLines],  
                            [NSNumber numberWithInt:CPTGraphLayerTypeAxisLines], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeAxisLabels], 
                            [NSNumber numberWithInt:CPTGraphLayerTypeAxisTitles], 
                            nil];
    graph.topDownLayerOrder = chartLayers;    
    
    
    // Add plot space for horizontal pie charts
    graph.paddingLeft = 80.0;
	graph.paddingTop = 100.0;//50.0
	graph.paddingRight = 70.0;
	graph.paddingBottom = 20.0;//60.0
    
    // Setup plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;
    plotSpace.delegate = self;
    
    //display last 6 months starting today
    plotSpace.xRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(oneDayInterval*0) 
                                                  length:CPTDecimalFromFloat(oneDayInterval*(initNumberOfDaysDisplayed-1))];
    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(100)];
    
    // Setup grid line style
    CPTMutableLineStyle *majorXGridLineStyle = [CPTMutableLineStyle lineStyle];
    majorXGridLineStyle.lineWidth = 1.0f;
    majorXGridLineStyle.lineColor = [[CPTColor grayColor] colorWithAlphaComponent:0.25f];
    
    // Setup x-Axis.
	CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x = axisSet.xAxis;
    x.majorGridLineStyle = majorXGridLineStyle;
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    
    //setup x axis label based on weeks; one label per 7 days
    
    x.majorIntervalLength = CPTDecimalFromFloat(oneDayInterval*30.0);
    x.minorTicksPerInterval = 0;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateStyle = kCFDateFormatterShortStyle; // format is mm/dd/yy
    CPTTimeFormatter *timeFormatter =[[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
    
    timeFormatter.referenceDate = initStartDate;
    x.labelFormatter = timeFormatter;
    
    
    // Setup y-Axis.
    CPTMutableLineStyle *majorYGridLineStyle = [CPTMutableLineStyle lineStyle];
    majorYGridLineStyle.lineWidth = 1.0f;
    majorYGridLineStyle.dashPattern =  [NSArray arrayWithObjects:[NSNumber numberWithFloat:5.0f], 
                                        [NSNumber numberWithFloat:5.0f], nil];
    majorYGridLineStyle.lineColor = [[CPTColor lightGrayColor] colorWithAlphaComponent:0.25];
    
    
    CPTXYAxis *y = axisSet.yAxis;
    
    y.majorGridLineStyle = majorYGridLineStyle;
    y.majorIntervalLength = CPTDecimalFromString(@"20");
    y.minorTicksPerInterval = 1;
    y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    y.title = @"Percent Current (%)";
    
    NSArray *yExlusionRanges = [NSArray arrayWithObjects:
                                [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0)
                                                             length:CPTDecimalFromFloat(0.0)], nil];
    y.labelExclusionRanges = yExlusionRanges;
    NSNumberFormatter *percentFormatter = [[NSNumberFormatter alloc] init];
    //[percentFormatter setNumberStyle:NSNumberFormatterPercentStyle];
    [percentFormatter setNumberStyle:NSNumberFormatterNoStyle];
    y.labelFormatter = percentFormatter;
    
    //y-axis stays in fixed position
    axisSet.yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0];
    
    
    // Create 1st plot area in Blue for balance
    currentPlot = [[CPTScatterPlot alloc] init];
    currentPlot.identifier = percentCurrentIdentifier;
    
    CPTMutableLineStyle *currentLineStyle = [currentPlot.dataLineStyle mutableCopy];
	currentLineStyle.lineWidth = 2.f;
    currentLineStyle.lineColor = [CPTColor colorWithComponentRed:0.051 green:0.388 blue:0.894 alpha:1.0]; //RGB: 13-99-228  (blue)
    
    currentPlot.dataLineStyle = currentLineStyle;
    currentPlot.dataSource = self;  
    
    CPTMutableShadow *blackShadow = [CPTMutableShadow shadow];
    blackShadow.shadowOffset	 = CGSizeMake(0.0, -7.0);
    blackShadow.shadowBlurRadius = 6.0;
    blackShadow.shadowColor		 = [CPTColor blackColor];
    currentPlot.shadow= blackShadow;    
    
    [graph addPlot:currentPlot];
    
    
    // Create the prior year plot
	priorYearPlot = [[CPTScatterPlot alloc] init];
    priorYearPlot.identifier = priorYearIdentifier;
    
	CPTMutableLineStyle *priorLineStyle = [currentPlot.dataLineStyle mutableCopy];
	priorLineStyle.lineWidth = 2.f;
    priorLineStyle.lineColor = [CPTColor colorWithComponentRed:0.078 green:0.529 blue:0.0 alpha:1.0]; //RGB: 20-135-0  (green)
    priorYearPlot.dataLineStyle = priorLineStyle;
    priorYearPlot.dataSource = self;  
    priorYearPlot.shadow = blackShadow; 
    
    
	
    // Create the percent 91 Days Delinquent Plot
	percent91DaysDelinquentPlot = [[CPTScatterPlot alloc] init];
    percent91DaysDelinquentPlot.identifier = percentOver91DaysDelinquentIdentifier;
    
	CPTMutableLineStyle *allLineStyle = [currentPlot.dataLineStyle mutableCopy];
	allLineStyle.lineWidth = 2.f;
	
    allLineStyle.lineColor = [CPTColor colorWithComponentRed:0.882 green:0.18 blue:0.137 alpha:1.0];   //RGB: 225-46-35  (orange)
    percent91DaysDelinquentPlot.dataLineStyle = allLineStyle;
    percent91DaysDelinquentPlot.dataSource = self;  
    percent91DaysDelinquentPlot.shadow = blackShadow;
	
    //create the ruler plot
    rulerPlot =  [[CPTScatterPlot alloc] initWithFrame:CGRectNull];
    rulerPlot.identifier = rulerPlotIdentifier;
    rulerPlot.dataSource = self;    
    
    //add legends
    currentPlot.title = @"Percent Current";
    priorYearPlot.title = @"Prior Year";	
    percent91DaysDelinquentPlot.title = @"Percent 91 Days Delinquent";
    
    CPTLegend *lineLegend = [CPTLegend legendWithPlots:[NSArray arrayWithObjects:currentPlot,                                                          
                                                        priorYearPlot,
                                                        percent91DaysDelinquentPlot,nil]]; 
	
    lineLegend.numberOfColumns = 3;
    graph.legend= lineLegend;
    graph.legend.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
    graph.legend.cornerRadius = 5.0;
    graph.legend.swatchSize = CGSizeMake(10.0, 10.0);
    graph.legendAnchor = CPTRectAnchorTop; 
    graph.legendDisplacement = CGPointMake(0.0, -80.0);  
    
    CPTMutableTextStyle *legendTextStyle = [[CPTMutableTextStyle alloc] init];
	legendTextStyle.color = [CPTColor darkGrayColor];
	legendTextStyle.fontSize = 11.0;
    legendTextStyle.fontName = @"Helvetica-Bold";
    graph.legend.textStyle = legendTextStyle;
    
}





@end
